package top.oylan.manager.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.oylan.manager.entity.*;
import top.oylan.manager.service.CategoryService;
import top.oylan.manager.service.ProductService;
import top.oylan.manager.service.SectionService;
import top.oylan.manager.tools.Directory;
import top.oylan.manager.tools.FileUploader;
import top.oylan.manager.tools.Pager;
import top.oylan.manager.tools.Result;
import top.oylan.manager.tools.enums.Types;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-09-14
 */
@Controller
@RequestMapping("/admin/book")
public class AdminBookController {

    @Resource
    CategoryService categoryService;

    @Resource
    ProductService productService;

    @Resource
    SectionService sectionService;

    @Resource
    JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 一览
     * @param page
     * @param limit
     * @param title
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String index(@RequestParam(value = "page",defaultValue = "1")Integer page,
                        @RequestParam(value = "limit",defaultValue = "12")Integer limit,
                        @RequestParam(value = "title",required = false)String title,
                        ModelMap modelMap){

        Pager pager = new Pager();
        Product condition = new Product();
        if (!StringUtils.isEmpty(title)) {
            condition.setTitle(title);
        }
        pager.setCondition(condition);
        pager.setCurrentPage(page);
        pager.setEveyPageRow(limit);
        List<Book> books = productService.selectBooksByPager(pager);
        pager.setList(books);
        modelMap.addAttribute("pager",pager);
        return "admin/book/list";
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(ModelMap modelMap){
        setCategories(modelMap);
        return "admin/book/add";
    }

    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public String edit(ModelMap modelMap,@RequestParam("id")Integer id){
        setCategories(modelMap);
        Course product = productService.selectProductById(id);
        Section condition = new Section();
        condition.setProductId(id);
        condition.setParentId(-1);
        condition.setLv((byte)2);
        List<Section> chapters = sectionService.selectSectionsByCondition(condition);
        modelMap.addAttribute("book",product);
        modelMap.addAttribute("chapters",chapters);
        return "admin/book/edit";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Result add(@RequestBody JSONObject movieJson){

        Result result = new Result();
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        JSONArray chapters = movieJson.getJSONArray("chapters");

        Product book = new Product();
        book.setTitle(movieJson.getString("title"));
        book.setType((byte)6);
        book.setCateId(movieJson.getShort("cateId"));
        book.setStatus(movieJson.getByte("status"));
        book.setCreateTime(new Date());
        book.setContent(movieJson.getString("content"));
        book.setDescription(movieJson.getString("description"));
        book.setPicture(movieJson.getString("picture"));
        book.setThumb(movieJson.getString("thumb"));
        book.setAuthorId(user.getId().shortValue());
        book.setScope((byte)2);
        int insert = productService.addProduct(book);
        if(insert > 0){
            for(int i=0;i<chapters.size();i++){
                Section section = new Section();
                JSONObject video = chapters.getJSONObject(i);
                section.setProductId(book.getId());
                section.setParentId(-1);
                section.setVedioUrl(video.getString("url"));
                section.setTitle(video.getString("title"));
                section.setLv((byte)2);
                section.setCreateTime(new Date());
                sectionService.saveSection(section);
            }
            result.setMessage("添加成功");
        }
        return result;

    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Result update(@RequestBody JSONObject jsonObject){
        Result result = new Result();
        JSONObject object = new JSONObject();
        object.put("productId",jsonObject.get("id"));
        object.put("id",-1);
        object.put("videos",jsonObject.getJSONArray("chapters"));

        jsonObject.remove("videos");

        Product product =  JSONObject.parseObject(jsonObject.toJSONString(),Product.class);
        productService.updateProduct(product);

        jmsMessagingTemplate.convertAndSend("queue.update_section_video",object.toJSONString());
        result.setCode((byte) 1);
        result.setMessage("更新成功");
        return result;
    }

    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public Result delete(@RequestParam("id")Integer id){

        return null;
    }

    private void setCategories(ModelMap modelMap) {

        List<Category> categories = categoryService.selectCategoriesForProduct(Types.BOOKS);
        modelMap.addAttribute("categories",categories);
    }

    @Resource
    FileUploader fileUploader;

    @RequestMapping("/upload")
    @ResponseBody
    public JSONObject upload(MultipartFile file){
        Result res = fileUploader.upload(file, Directory.BOOK);
        JSONObject object = new JSONObject();
        object.put("status",1);
        if(res.getCode() == 1){
            object.put("path",res.getData().get("path").toString());
        }else{
            object.put("status",0);
        }
        return object;
    }
}
